package main

import (
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/grpclog"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"Gocode/study.com/RPCandgRPC/grpc/Token/message"
	"net"
)

type Person struct {

}

func (u *Person) GetUser(ctx context.Context, request *message.UserRequest)(*message.User, error) {


	user := message.User{Name: request.Name, Age: request.Age, Gender: message.Gender(request.Gender)}
	return &user, nil
}

func TokenInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error){
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok{
		return nil, status.Error(codes.Unauthenticated, "无Token认证信息")
	}
	var (
		appKey string
		appSecret string
	)
	key, ok := md["appid"]
	if ok{
		appKey = key[0]
	}
	if secret, ok := md["appkey"]; ok{
		appSecret = secret[0]
	}
	if appKey != "goToken" || appSecret != "goSecret" {
		return nil, status.Errorf(codes.Unauthenticated, "Token 不合法")
	}
	//通过token验证，继续处理请求
	return handler(ctx, req)
}

func main() {
	//TLS认证
	//TODO 此处为什么相对路径会有err？
	creds, err := credentials.NewServerTLSFromFile("E:\\Goproject\\src\\learn\\RPCandgRPC\\grpc\\SSLAndTLS\\SSL\\keys\\server.pem", "E:\\Goproject\\src\\learn\\RPCandgRPC\\grpc\\SSLAndTLS\\SSL\\keys\\server.key")
	if err != nil {
		grpclog.Fatal("加载在证书文件失败", err)
	}

	//实例化grpc server, 开启TLS认证,并传如拦截器
	server := grpc.NewServer(grpc.Creds(creds), grpc.UnaryInterceptor(TokenInterceptor))

	message.RegisterGetUserServiceServer(server, new(Person))

	lis, err := net.Listen("tcp", ":9000")
	if err != nil {
		panic(err.Error())
	}
	server.Serve(lis)

}

